<template>
    <h2>{{ videoInfo?.title }}</h2>
    <div class="rich-box" v-html="videoInfo?.description"></div>
    <!-- <VideoPlayer v-if="videoInfo && videoInfo.can_watch" :videoInfo="videoInfo" :videoId="videoId" /> -->

    <div class="iframe-box">
        <iframe
            id="panopto-player"
            ref="panoptoIframe"
            :src="
                videoInfo?.panopto_video_embed_code +
                '&remoteEmbed=true&remoteHost=https%3A%2F%2Flms.bingo-test.com&embedApiId=panopto-player&interactivity=none&showtitle=false&offerviewer=false&instance=batprog&enableApi=true'
            "
            frameborder="0"
            border="0"
            scrolling="no"
        ></iframe>
    </div>
    <div class="btn-list" v-if="videoInfo && !videoInfo.can_watch">
        <el-button color="#F06423" @click="goPage(`/console/course/${courseId}/unit/${unitId}/videoTime/${videoInfo.should_watch_video_id}`)">前往可以查看的視頻頁</el-button>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

import ResourceService from '@/api/resource'
import type { VideoInfo } from '@/types/resource'

import { goPage } from '@/utils/global'

import VideoPlayer from '@/components/VideoPlayer.vue'

const route = useRoute()
const courseId = computed(() => Number(route.params.courseId))
const unitId = computed(() => Number(route.params.unitId))
const videoId = computed(() => Number(route.params.videoId))
const videoInfo = ref<VideoInfo | null>()
const loading = ref(false)
const panoptoIframe = ref<HTMLIFrameElement | null>(null)

// Panopto API 相关
let embedApi: any = null
let maxWatchedTime = 0
let storageKey = ''

// 声明全局类型
declare global {
    interface Window {
        EmbedApi: any
    }
}

function getVideoInfo() {
    loading.value = true
    videoInfo.value = null
    ResourceService.videoInfo(videoId.value)
        .then(res => {
            videoInfo.value = res
            // 视频信息加载后，初始化 Panopto API
            nextTick(() => {
                initPanoptoPlayer()
            })
        })
        .finally(() => {
            loading.value = false
        })
}

// 初始化 Panopto 播放器
function initPanoptoPlayer() {
    if (!videoInfo.value || !videoInfo.value.panopto_video_id) {
        return
    }

    // 等待 iframe 加载完成
    const iframe = document.getElementById('panopto-player') as HTMLIFrameElement
    if (!iframe) {
        console.error('找不到 Panopto iframe')
        return
    }

    // 加载 Panopto EmbedApi 脚本
    loadPanoptoScript()
        .then(() => {
            // 再次检查，确保 API 可用
            if (!window.EmbedApi) {
                console.error('Panopto EmbedApi 加载失败')
                return
            }

            // 生成存储 key
            storageKey = `panopto_progress_${videoInfo.value!.panopto_video_id}`

            // 从 localStorage 或后端进度获取最大观看时间
            const savedTime = localStorage.getItem(storageKey)
            const backendProgress = videoInfo.value?.progress?.last_position || 0

            // 优先使用后端进度，如果没有则使用 localStorage
            maxWatchedTime = backendProgress > 0 ? backendProgress : savedTime ? parseFloat(savedTime) : 0

            // 初始化 EmbedApi
            try {
                embedApi = new window.EmbedApi('panopto-player', {
                    width: '100%',
                    height: '100%',
                    serverName: 'eduhk.ap.panopto.com',
                })

                // 播放器准备就绪
                embedApi.write('ready', function () {
                    console.log('Panopto Player Ready')

                    // 可选：如果用户上次看过，自动跳转到上次位置
                    // if (maxWatchedTime > 5) {
                    //     embedApi.seekTo(maxWatchedTime)
                    // }
                })

                // 监听时间更新事件
                embedApi.write('onTimeUpdate', function (currentTime: number) {
                    // 如果允许快进，则不限制
                    if (videoInfo.value?.allow_fast_forward === 1) {
                        // 允许快进时，仍然记录进度
                        if (currentTime > maxWatchedTime) {
                            maxWatchedTime = currentTime
                            localStorage.setItem(storageKey, maxWatchedTime.toString())
                        }
                        return
                    }

                    // 禁止快进逻辑
                    // 允许的狀況：正常播放 (當前時間 <= 最大紀錄 + 緩衝2秒)
                    if (currentTime <= maxWatchedTime + 2) {
                        // 如果當前時間大於紀錄，更新紀錄 (代表使用者正在看新的內容)
                        if (currentTime > maxWatchedTime) {
                            maxWatchedTime = currentTime

                            // 儲存到 localStorage
                            localStorage.setItem(storageKey, maxWatchedTime.toString())
                        }
                    }
                    // 禁止的狀況：偷跑 (當前時間 > 最大紀錄 + 緩衝)
                    else {
                        console.warn('偵測到快轉！')

                        // 強制拉回
                        embedApi.seekTo(maxWatchedTime)

                        // 顯示警告 UI
                        showWarningToast()
                    }
                })
            } catch (error) {
                console.error('初始化 Panopto EmbedApi 失败:', error)
            }
        })
        .catch(error => {
            console.error('加载 Panopto 脚本失败:', error)
        })
}

// 加载 Panopto EmbedApi 脚本
function loadPanoptoScript(): Promise<void> {
    return new Promise((resolve, reject) => {
        // 检查是否已经加载
        if (window.EmbedApi) {
            resolve()
            return
        }

        // 检查脚本是否已经在 DOM 中
        const existingScript = document.querySelector('script[src*="EmbedApi.js"]') as HTMLScriptElement
        if (existingScript) {
            // 如果 API 已经可用，直接 resolve
            if (window.EmbedApi) {
                resolve()
                return
            }
            // 等待脚本加载
            existingScript.addEventListener('load', () => resolve())
            existingScript.addEventListener('error', reject)
            return
        }

        // 创建并加载脚本
        const script = document.createElement('script')
        script.src = 'https://eduhk.ap.panopto.com/Panopto/Pages/Embed/EmbedApi.js'
        script.onload = () => resolve()
        script.onerror = reject
        document.head.appendChild(script)
    })
}

// 显示警告提示
function showWarningToast() {
    ElMessage.warning('⚠️ 您尚未觀看此片段，無法快轉！')
}

watch(videoId, () => {
    // 清理之前的 API 实例
    if (embedApi) {
        embedApi = null
    }
    getVideoInfo()
})

onMounted(() => {
    getVideoInfo()
})

onUnmounted(() => {
    // 清理资源
    if (embedApi) {
        embedApi = null
    }
})
</script>

<style lang="less" scoped>
h2 {
    margin-bottom: 30px;
    font-size: 30px;
    font-weight: normal;
    line-height: 1.2;
    color: #000;
}

.iframe-box {
    position: relative;

    &::after {
        content: '';
        display: block;
        padding-top: 56.25%;
    }

    iframe {
        width: 100%;
        height: 100%;
        overflow: hidden;

        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
}

.btn-list {
    display: flex;
    margin-top: 15px;
}
</style>
